/*
 *    Copyright 2009-2022 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.scripting.xmltags;

/**
 * 对应的动态 SQL 节点是＜if>节点
 * @author Clinton Begin
 */
public class IfSqlNode implements SqlNode {
  /**
   * ExpressionEvaluator 对象用于解析＜ if ＞节点 test 表达式的值
   */
  private final ExpressionEvaluator evaluator;

  /**
   * 记录了 if ＞节点 中的 test 表达式
   */
  private final String test;

  /**
   * 记录了＜ if ＞节点的子节点
   */
  private final SqlNode contents;

  public IfSqlNode(SqlNode contents, String test) {
    this.test = test;
    this.contents = contents;
    this.evaluator = new ExpressionEvaluator();
  }

  /**
   * 法首先会通过 ExpressionEvaluator.evaluateBoolean（） 方法检测其 test 表达
   * 式是否为 true ，然后根据 test 表达式的结果，决定是否执行其子节点的 apply（）方法
   */
  @Override
  public boolean apply(DynamicContext context) {
    // 1. 检测 test 属性 中记录的表达式
    if (evaluator.evaluateBoolean(test, context.getBindings())) {
      // 2. test 表达式为 true, 则执行子节点的 apply （）方法
      contents.apply(context);
      return true;
    }

    // 3. 注意返回值，表示的是 test 表达式是否为 true
    return false;
  }

}
